package controllers

import (
	"gitee.com/igolang/imoney/internal/app/system/services"
	"gitee.com/igolang/imoney/internal/common/httpResp"
	"gitee.com/igolang/imoney/internal/models/dao"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"strings"
)

var Post = &post{}

type post struct{}

func (c *post) List(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	data, err := services.Post.List(ctx)
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	r.Data = data
}

func (c *post) Detail(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	id := cast.ToInt64(ctx.Param("id"))
	if id == 0 {
		httpResp.ErrorResponse(httpResp.ErrCodeInvalidParams, r)
		return
	}
	row, err := dao.SysPost.Where(dao.SysPost.PostID.Eq(id)).Take()
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	r.Data = row
}

func (c *post) Add(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	if err := services.Post.Save(ctx); err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
}

func (c *post) Update(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	if err := services.Post.Save(ctx); err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}

}

func (c *post) Delete(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	idArr := strings.Split(ctx.Param("ids"), ",")
	if len(idArr) == 0 {
		httpResp.ErrorResponse(httpResp.ErrCodeInvalidParams, r)
		return
	}

	id := make([]int64, 0)
	for _, v := range idArr {
		id = append(id, cast.ToInt64(v))
	}
	if count, _ := dao.SysUserPost.Where(dao.SysUserPost.PostID.In(id...)).Count(); count > 0 {
		httpResp.ErrorResponse("待删除的岗位已分配，无法删除", r)
		return
	}

	_, err := dao.SysPost.Where(dao.SysPost.PostID.In(id...)).Delete()
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
}

func (c *post) Export(ctx *gin.Context) {
	r := httpResp.Response()
	b, err := services.Post.Export(ctx)
	if err != nil {
		httpResp.ErrorResponse(err, r)
		httpResp.JSON(ctx, r)
		return
	}

	httpResp.Export(ctx, b, "xlsx")
}
